using Microsoft.EntityFrameworkCore;
using AdminSystem.API.Data;
using AdminSystem.API.DTOs;
using AdminSystem.API.Models;
using AutoMapper;

namespace AdminSystem.API.Services
{
    public class PermissionService : IPermissionService
    {
        private readonly ApplicationDbContext _context;
        private readonly IMapper _mapper;

        public PermissionService(ApplicationDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<List<PermissionDto>> GetAllPermissionsAsync()
        {
            var permissions = await _context.Permissions
                .Where(p => p.IsActive)
                .ToListAsync();

            return _mapper.Map<List<PermissionDto>>(permissions);
        }

        public async Task<PermissionDto?> GetPermissionByIdAsync(int id)
        {
            var permission = await _context.Permissions.FindAsync(id);
            return permission == null ? null : _mapper.Map<PermissionDto>(permission);
        }

        public async Task<PermissionDto> CreatePermissionAsync(CreatePermissionDto createPermissionDto)
        {
            var permission = new Permission
            {
                Name = createPermissionDto.Name,
                Description = createPermissionDto.Description,
                Resource = createPermissionDto.Resource,
                Action = createPermissionDto.Action,
                IsActive = true,
                CreatedAt = DateTime.UtcNow
            };

            _context.Permissions.Add(permission);
            await _context.SaveChangesAsync();

            return _mapper.Map<PermissionDto>(permission);
        }

        public async Task<PermissionDto?> UpdatePermissionAsync(int id, UpdatePermissionDto updatePermissionDto)
        {
            var permission = await _context.Permissions.FindAsync(id);
            if (permission == null)
                return null;

            permission.Name = updatePermissionDto.Name;
            permission.Description = updatePermissionDto.Description;
            permission.Resource = updatePermissionDto.Resource;
            permission.Action = updatePermissionDto.Action;
            permission.IsActive = updatePermissionDto.IsActive;

            await _context.SaveChangesAsync();

            return _mapper.Map<PermissionDto>(permission);
        }

        public async Task<bool> DeletePermissionAsync(int id)
        {
            var permission = await _context.Permissions.FindAsync(id);
            if (permission == null)
                return false;

            permission.IsActive = false;
            await _context.SaveChangesAsync();

            return true;
        }
    }
}
